package core

import (
	"errors"
	"os"
	"sync"

	"github.com/CIPFZ/collector/pkg/exception"
)

// TaskStatusManager 管理任务状态
type TaskStatusManager struct {
	file  *StatusFileStorage
	cache *Cache
	mutex sync.Mutex
}

func NewTaskStatusManager(dir string, cache bool) *TaskStatusManager {
	manager := &TaskStatusManager{
		file:  NewStatusFileStorage(dir),
		cache: nil,
	}
	if cache {
		manager.cache = NewCache()
	}
	return manager
}

// CreateTask 初始化任务状态
func (m *TaskStatusManager) CreateTask(taskID string, jobIDs []string) (*Task, error) {
	m.mutex.Lock()
	defer m.mutex.Unlock()

	return nil, nil
}

// UpdateJob 更新 job 状态
func (m *TaskStatusManager) UpdateJob(taskID, jobID, status, message string) error {
	m.mutex.Lock()
	defer m.mutex.Unlock()

	return nil
}

// GetTaskStatus 获取任务状态
func (m *TaskStatusManager) GetTaskStatus(taskID string) (*Task, error) {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	return m.getTask(taskID)
}

// 内部方法：优先用缓存，否则读文件
func (m *TaskStatusManager) getTask(taskID string) (*Task, error) {
	if task, ok := m.cache.Get(taskID); ok {
		return task, nil
	}
	task, err := m.file.Load(taskID)
	if err != nil {
		if errors.Is(err, os.ErrNotExist) {
			return nil, exception.NewTaskStatusFileNotFoundError(taskID)
		}
		return nil, err
	}
	m.cache.Set(task)
	return task, nil
}

// RemoveTaskStatusFile 删除收集任务状态文件
func (m *TaskStatusManager) RemoveTaskStatusFile(taskID string) error {
	return m.file.Remove(taskID)
}
